package com.SHA1604.tiger.activity;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.SHA1604.tiger.R;
import com.SHA1604.tiger.base.BaseActivity;
import com.SHA1604.tiger.fragment.FindFragment;
import com.SHA1604.tiger.fragment.HomeFragment;
import com.SHA1604.tiger.fragment.MeFragment;
import com.SHA1604.tiger.fragment.SeaAmoyFragment;
import com.SHA1604.tiger.fragment.SunFragment;

import java.util.ArrayList;
import java.util.List;

public class FragmentActivity extends BaseActivity{
    private List<Fragment> mDatas;
    private RadioGroup mRg_tab;
    private int previousIndex;
    @Override
    protected void initView() {
        setContentView(R.layout.activity_fragment);
        mRg_tab = (RadioGroup) findViewById(R.id.rg_tab);
    }
    @Override
    protected void initData() {
        mDatas = new ArrayList<>();
        mDatas.add(new HomeFragment());
        mDatas.add(new SeaAmoyFragment());
        mDatas.add(new SunFragment());
        mDatas.add(new FindFragment());
        mDatas.add(new MeFragment());

        previousIndex = 0;
        showFragment(0,previousIndex);
        ((RadioButton) mRg_tab.getChildAt(previousIndex)).setChecked(true);

    }
    @Override
    protected void setListener() {
        mRg_tab.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton rb = (RadioButton) group.findViewById(checkedId);
                int index = group.indexOfChild(rb);
                showFragment(index, previousIndex);
                previousIndex = index;
            }
        });
    }

    public void showFragment(int currentIndex,int previousIndex){
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment showFragment = mDatas.get(currentIndex);
        Fragment hideFragment = mDatas.get(previousIndex);
        if (!showFragment.isAdded()){
            ft.add(R.id.fl_container,showFragment);
        }
        if (showFragment==hideFragment){
            ft.show(showFragment).commit();
            return;
        }
        ft.show(showFragment).hide(hideFragment).commit();
    }

}
